// pages/realname/noreal.js
var {
  http
} = require('../../utils/apiutils');
const qiniu = require("../../utils/qnutils");

const app = getApp()

import { formatTime } from '../../utils/util'
var baidu = require('../../utils/bdutils.js')

Component({
  /**
   * 组件的属性列表
   */
  properties: {

  },
  lifetimes: {
    // 生命周期函数，可以为函数，或一个在methods段中定义的方法名
    attached: function () {
      this.getUpToken();
      baidu.getoAuthToken();
    },
    moved: function () { },
    detached: function () { },
  },
  /**
   * 组件的初始数据
   */
  data: {
    zmimg: "",
    qnzmimg: "",
    qnfmimg: "",
    fmimg: "",
    zm: false,
    fm: false,
    show: false,
    token: "",
    member: {
      "idNumber": "", //身份证号
      "name": "", //姓名
      "nation": "", //名族
      "nativePlace": "", //籍贯
      "sex": "", //性别
      "start_time": "",
      "end_time": "",
      "signing": "",
      "reverseUrl": "",
      "frontUrl": ""
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    getUpToken: function () {
      var that = this;
      http.getUpToken({},
        function (res) {
          console.log("----七牛云的授权码---", res);
          that.data.token = res.data;
          qiniu.initQiniu(res.data);
        },
        function (err) {

        })
    },

    baiduUpdate: function (data, type) {
      var that = this;
      baidu.sumbitImgToBadu(data,
        function (res) {
          console.log("----返回照片的信息---", res);
          if (type == 1) {
            if (res.words_result) {
              let w = res.words_result;
              if (w["公民身份号码"] && w["公民身份号码"].words != "") {

                that.data.member.idNumber = w["公民身份号码"].words;
              } else {
                that.setData({
                  show: true,
                })
                return;

              }
              if (w["姓名"] && w["姓名"].words != "") {
                that.data.member.name = w["姓名"].words;
              } else {
                that.setData({
                  show: true,
                })
                return;

              }
              if (w["住址"] && w["住址"].words != "") {
                that.data.member.nativePlace = w["住址"].words;
              } else {
                that.setData({
                  show: true,
                })
                return;

              }
              if (w["民族"] && w["民族"].words != "") {
                that.data.member.nation = w["民族"].words;
              } else {
                that.setData({
                  show: true,
                })
                return;
              }
              if (w["性别"] && w["性别"].words != "") {
                that.data.member.sex = w["性别"].words;
              } else {
                that.setData({
                  show: true,
                })
                return;
              }
              var base64 = 'data:image/jpg;base64,' + wx.getFileSystemManager().readFileSync(that.data.fmimg, "base64");
              // console.log("----", base64);
              var p = {
                image: base64,
                id_card_side: "back",
              }
              that.baiduUpdate(p, 2)
              // console.log("---",that.data.member);
            } else {
              that.setData({
                show: true,
              })
              return;
            }
          } else if (type == 2) {
            if (res.words_result) {
              let w = res.words_result;
              console.log(w)
              if (w["失效日期"] && w["失效日期"].words != "" && w["失效日期"].words != "长期") {
                that.data.member.idCardEndDate = `${w["失效日期"].words.substr(0, 4)}-${w["失效日期"].words.substr(4, 2)}-${w["失效日期"].words.substr(6,)}`;
              } else if (w["失效日期"].words == "长期") {
                that.data.member.idCardEndDate = "长期";
              } else {

              }
              if (w["签发日期"] && w["签发日期"].words != "") {
                that.data.member.idCardStartDate = `${w["签发日期"].words.substr(0, 4)}-${w["签发日期"].words.substr(4, 2)}-${w["签发日期"].words.substr(6,)}`;
              } else {
                that.setData({
                  show: true,
                })
                return;
              }
              if (w["签发机关"] && w["签发机关"].words != "") {
                that.data.member.idCardOrganization = w["签发机关"].words;
              } else {
                that.setData({
                  show: true,
                })
                return;
              }
              that.userAttestation();
              //开始实名认证
            } else {
              that.setData({
                show: true,
              })
              return;
            }
          }
        },
        function (err) {
          wx.showToast({
            title: '身份认证失败',
            icon: "none",
          })
        })
    },
    userAttestation: function () {
      var that = this;
      var prams = this.data.member;
      http.userAttestation(prams,
        function (res) {
          console.log("----实名认证成功---", res);
          // that.data.token = res.data;
          // that.getUpToken();
          if (res.status == 200) {
            that.upDataImage(that.data.zmimg, 1)
            wx.showToast({
              title: res.message,
              icon: "none"
            })
          } else if (res.status == 202) {
            wx.showModal({
              title: '提示',
              content: '已存在实名认证，确定与原用户绑定么？',
              success: function (res) {
                if (res.confirm) {
                  that.reSetUser()
                }
              }
            })
          } else {
            wx.showToast({
              title: res.message,
              icon: "none"
            })
          }
        },
        function (err) {

        })

    },
    reSetUser() {
      wx.navigateTo({
        url: '/pages/login/login?idNumber=' + this.data.member.idNumber + '&type=4',
      })
    },
    upDataImage: function (tempFilePaths, type) {
      var that = this;
      qiniu.getUploadImgae(tempFilePaths,
        function (res) {
          if (res.error) {
            wx.showToast({
              title: '图片上传失败，请重新认证',
              icon: "none"
            })
            return
          }
          console.log("-------上传七牛云返回数据---", res)
          if (type == 1) {
            // that.data.qnzmimg = res.imageURL;
            that.data.member.fronqiniutUrl = res.key;
            var data = {
              "photo": res.key, //证件照地址
              "type": 1 //1.正面    2.反面
            }
            that.setIdPhoto(data, 1);
            that.upDataImage(that.data.fmimg, 2)
          } else if (type == 2) {
            that.data.member.reverseUrl = res.key;
            var data = {
              "photo": res.key, //证件照地址
              "type": 2 //1.正面    2.反面
            }
            that.setIdPhoto(data, 2);
          }
          console.log("----上传成功---", res);

        },
        function (err) { })
    },
    setIdPhoto: function (data, type) {
      var that = this;
      http.setIdPhoto(data,
        function (res) {
          console.log("--------认证成功---", type, res, res.status == "200");
          if (res.status == "200") {
            if (type == 2) {
              wx.reLaunch({
                url: '/pages/index/index',
                success: function () {
                  app.globalData.userInfo.idNumber = that.data.member.idNumber
                  wx.showToast({
                    title: '实名认证成功',
                    icon: "none",
                  })
                }
              })
            }
          }
          else {

            wx.showToast({
              title: res.message,
              icon: "none",
            })
          }
          // wx.navigateBack({
          //   delta: 2,
          // })
          // let app = getApp();
          // app.globalData.userInfo.name = that.data.member.name;
          // app.globalData.userInfo.sex = that.data.member.sex;
          // app.globalData.userInfo.nation = that.data.member.nation;
          // app.globalData.userInfo.idNumber =that.data.member.idNumber
          // app.globalData.userInfo.nativePlace = that.data.member.nativePlace
          // app.globalData.userInfo.reverseUrl = that.data.member.reverseUrl
          // app.globalData.userInfo.frontUrl = that.data.member.frontUrl

          // that.triggerEvent("opSuccess",that.data.member);
          // console.log("----实名认证成功---", res);
        },
        function (err) {

        })
    },
    onClickSumbit: function () {
      // this.setData({
      //   show: true,
      // })
      var base64 = 'data:image/jpg;base64,' + wx.getFileSystemManager().readFileSync(this.data.zmimg, "base64");
      console.log("----", base64);
      var data = {
        image: base64,
        id_card_side: "front",
      }
      this.baiduUpdate(data, 1)

    },
    onClose: function () {
      this.setData({
        show: false,
      })
    },
    onClickImg: function (e) {
      var type = e.currentTarget.dataset.type;
      console.log("----------2222---", type);
      var that = this;
      wx.chooseImage({
        count: 1, // 默认9
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        success: function (res) {
          // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
          if (res.tempFilePaths.count == 0) {
            return;
          }
          var tempFilePaths = res.tempFilePaths[0];
          if (type == 1) {
            that.setData({
              zm: true,
              zmimg: tempFilePaths
            })
            console.log("-------------", that.data.zm, that.data.zmimg)
          } else {
            that.setData({
              fm: true,
              fmimg: tempFilePaths
            })
          }
        }
      })
    }
  }
})